# coding:utf-8
import os
import sys
from enum import Enum

from PyQt5.QtCore import QLocale
from qfluentwidgets import (
    qconfig,
    QConfig,
    ConfigItem,
    OptionsConfigItem,
    BoolValidator,
    OptionsValidator,
    Theme,
    FolderValidator,
    ConfigSerializer,
)

from .setting import CONFIG_FILE, CONFIG_FOLDER, ENCRYPTION_STATION


class Language(Enum):
    """Language enumeration"""

    CHINESE_SIMPLIFIED = QLocale(QLocale.Chinese, QLocale.China)
    CHINESE_TRADITIONAL = QLocale(QLocale.Chinese, QLocale.HongKong)
    ENGLISH = QLocale(QLocale.English)
    AUTO = QLocale()


class LanguageSerializer(ConfigSerializer):
    """Language serializer"""

    def serialize(self, language):
        return language.value.name() if language != Language.AUTO else "Auto"

    def deserialize(self, value: str):
        return Language(QLocale(value)) if value != "Auto" else Language.AUTO


def isWin11():
    return sys.platform == "win32" and sys.getwindowsversion().build >= 22000


class Config(QConfig):
    """Config of application"""

    # TODO: ADD YOUR CONFIG GROUP HERE

    # register
    rememberMe = ConfigItem("Register", "RememberMe", True)
    email = ConfigItem("Register", "Email", "")
    activationCode = ConfigItem("Register", "ActivationCode", "")

    # main window
    micaEnabled = ConfigItem("MainWindow", "MicaEnabled", isWin11(), BoolValidator())
    dpiScale = OptionsConfigItem(
        "MainWindow",
        "DpiScale",
        "Auto",
        OptionsValidator([1, 1.25, 1.5, 1.75, 2, "Auto"]),
        restart=True,
    )
    language = OptionsConfigItem(
        "MainWindow",
        "Language",
        Language.AUTO,
        OptionsValidator(Language),
        LanguageSerializer(),
        restart=True,
    )

    # software update
    checkUpdateAtStartUp = ConfigItem(
        "Update", "CheckUpdateAtStartUp", True, BoolValidator()
    )


# 读取用户信息
class readUserInformation:
    def __init__(self) -> None:
        self.configFolder = CONFIG_FOLDER
        self.userInformationFile = str(self.configFolder) + "userInformation.bin"

    def _fileExist(self, path):
        return os.path.exists(path)

    def createFile(self):
        with open(self.userInformationFile, "wb") as f:
            f.write(b"")

    def readFile(self):
        if self._fileExist(self.userInformationFile):
            with open(self.userInformationFile, "rb") as f:
                result = f.read()
                deresult = ENCRYPTION_STATION.decrypt(result).decode()
                deresult = eval(deresult)

        else:
            deresult = None
        return deresult


cfg = Config()
cfg.themeMode.value = Theme.AUTO
qconfig.load(str(CONFIG_FILE.absolute()), cfg)
